package com.example.competitionregistration.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.example.competitionregistration.common.ErrorCode;
import com.example.competitionregistration.common.Result;
import com.example.competitionregistration.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Author QuanJingFang
 * @Description //TODO 拦截器,除登录，注册页面，其他页面都进行拦截
 * @Date 2023/7/15 20:37
 **/
@Component
public class Interceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url=request.getRequestURI();
        if(url.contains("login")||url.contains("register")||url.contains("download")){
            return true;
        }
        String jwt = request.getHeader("token");
        if (!StringUtils.hasLength(jwt)) {
            Result result = Result.error(ErrorCode.NO_LOGIN_ERROR.getCode(), ErrorCode.NO_LOGIN_ERROR.getMsg());
            String noLogin = JSONObject.toJSONString(result);
            response.reset();
            response.setContentType("test/html;charset=utf-8");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Headers", "*");
            response.getWriter().write(noLogin);
            return false;
        }
        Claims claims;
        try {
            claims = JwtUtil.parse(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            Result result = Result.error(ErrorCode.JWT_ERROR.getCode(), ErrorCode.JWT_ERROR.getMsg());
            String noLogin = JSONObject.toJSONString(result);
            response.reset();
            response.setContentType("test/html;charset=utf-8");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Headers", "*");
            response.getWriter().write(noLogin);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
